package org.speed.jdk;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;


public class Uuid {
	
	private static Uuid INSTANCE = null;
	private Long lastUpdateTime = System.currentTimeMillis();
	private Long lastUpdateMills = lastUpdateTime / 1000 * 1000;
	private AtomicInteger seq = new AtomicInteger(1000);
	
	private Uuid(){
		
	}
	
	public static Uuid getInstance() {
		if(INSTANCE == null ) {
			synchronized (Uuid.class) {
				if(INSTANCE == null ) {
					INSTANCE = new Uuid();
				}
			}
		}
		return INSTANCE;
	}
	
	public synchronized String get21Uuid() {
		long time = System.currentTimeMillis();
		while(time < lastUpdateTime ) {
			time = System.currentTimeMillis();
		}
		lastUpdateTime = time;
		
		long temp = time / 1000 * 1000;
		SimpleDateFormat sdfDateFormat = new SimpleDateFormat("yyMMddHHmmss");
		String t1 = sdfDateFormat.format(new Date(time));		
		String t2 = fillZero((time - temp) + "",3);
		
		if(lastUpdateMills != temp ) {
			seq = new AtomicInteger(1000);
		}
		lastUpdateMills = temp;
		
		String t3 = fillZero(seq.incrementAndGet() + "",6);
		StringBuffer sdf = new StringBuffer();
		return sdf.append(t1).append(t2).append(t3).toString();
	}
	
	
	private String fillZero(String s,int size) {
		StringBuffer sbf = new StringBuffer();
		if(s.length() < size ) {
			int length = s.length();
			for(int i = 0 ; i < size - length ; i ++ ) {
				sbf.append("0");
			}
		}
		sbf.append(s);
		return sbf.toString();
	}
	
	public static void main(String[] args) {
		long start = System.currentTimeMillis();
		Set<String> sets = new HashSet<String>();
		Uuid uuid = Uuid.getInstance();
		for(int i = 0 ; i < 1000000 ; i++ ) {
			String id = uuid.get21Uuid();
			sets.add(id);
			System.out.println(id);
		}
		long end = System.currentTimeMillis();
		System.out.println("time=" + (end - start) + "ms");
		System.out.println(sets.size());
	}

}
